package com.blackhorse.controller;

import com.alibaba.fastjson.JSON;
import com.blackhorse.domain.Order;
import com.blackhorse.domain.Product;
import com.blackhorse.service.OrderService;
import com.blackhorse.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 测试高并发场景的controller
 * 使用时打开RestController注解
 */
@Slf4j
//@RestController
public class OrderController2 {

    @Autowired
    private OrderService orderService;
    /**
     * 可直接注入Feign的远程调用接口
     */
    @Autowired
    private ProductService productService;

    /**
     * 用户下单接口
     */
    @RequestMapping("/order/prod/{pid}")
    public Order order(@PathVariable("pid") Integer pid) {
        log.info("订单微服务-下单-开始 pid:{}", pid);

        Product product = productService.findByPid(pid);

        try {
            //模拟调用商品微服务需要2s左右时间
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        log.info("订单微服务-下单-查询到商品信息 pid:{} product:{}", pid, JSON.toJSONString(product));

        if (product == null) {
            throw new IllegalArgumentException("商品不存在");
        }
        Order order = new Order();
        order.setUid(1);
        order.setUsername("测试用户");
        order.setPid(pid);
        order.setPname(product.getPname());
        order.setPprice(product.getPprice());
        order.setNumber(1);
        //不产生大量测试数据，先注释这行代码
//        orderService.createOrder(order);

        log.info("订单微服务-下单-创建订单成功 order:{}", JSON.toJSONString(order));
        return order;
    }

    /**
     * 测试高并发下其他接口阻塞的情况，使用jmeter压测/order/prod/1接口，访问/order/message接口响应也很慢
     */
    @RequestMapping("/order/message")
    public String message() {
        return "测试message";
    }
}
